<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/12
 * Time: 14:17
 */
namespace App\Service\Api;

use App\Http\Model\Mysql\CouponModel;
use App\Http\Model\Mysql\UserCouponModel;
use App\Http\Model\Mysql\CouponConnectionModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class CouponService extends BaseService
{
    /**
     * 获取指定商品的优惠券
     * @param array $good_id    商品ID组
     * @param int|null $shop_id 店铺ID
     * @return array
     */
    public function _couponSpecific(array $good_id, int $shop_id = NULL)
    {
        //查看所有商品指定的优惠券
        $coupon_model   =   CouponConnectionModel::query()->where(['connect_type' => CouponConnectionModel::GOOD_CONNECT])->whereIn('connect_id', $good_id);

        if (!empty($shop_id)) {
            $coupon_model   =   $coupon_model->orWhere(function ($query) use($shop_id){
                $query->where(['connect_type' => CouponConnectionModel::SHOP_CONNECT])->where('connect_id', $shop_id);
            });
        }

        $connect_list    =   $coupon_model->get('id')->toArray();
        if (!empty($connect_list)) {
            $coupon_id   =   [];
            foreach ($connect_list as $item) {
                $coupon_id[]    =   $item['id'];
            }
            $coupon_list    =   CouponModel::query()->center()->whereIn('id', $coupon_id)->select(['id', 'unique_id', 'name', 'picture', 'type', 'scene', 'min_price', 'sub_price', 'discount', 'expire_type', 'expire_day', 'begin_time', 'end_time'])
                                ->orderBy('sorting', 'desc')->get()->each(function (&$item) {
                                    $item->begin_time   =   Carbon::createFromTimestamp($item->begin_time)->toDateTimeString();
                                    $item->end_time     =   Carbon::createFromTimestamp($item->end_time)->toDateTimeString();
                                });
            return [true, $coupon_list->isEmpty() ? [] : $coupon_list->toArray()];
        } else {
            return [true, []];
        }
    }

    /**
     * 获取指定商品的优惠券
     * @param array $good_id    商品ID组
     * @param int|null $user_id      用户ID
     * @param int|null $shop_id 店铺ID
     * @return array
     */
    public function couponSpecific(array $good_id, int $user_id = NULL, int $shop_id = NULL)
    {
        //查看所有商品指定的优惠券
        $coupon_model   =   CouponConnectionModel::with([
                                'coupon' => function ($query) {
                                    $query->center()->select(['id', 'unique_id', 'name', 'desc', 'type', 'scene', 'min_price', 'sub_price', 'discount', 'expire_type', 'expire_day', 'user_num', DB::raw('from_unixtime(begin_time) as begin_time'), DB::raw('from_unixtime(end_time) as end_time')]);
                                }
                            ])->where(['connect_type' => CouponConnectionModel::GOOD_CONNECT])->whereIn('connect_id', $good_id);

        if (!empty($shop_id)) {
            $coupon_model   =   $coupon_model->orWhere(function ($query) use($shop_id){
                $query->where(['connect_type' => CouponConnectionModel::SHOP_CONNECT])->where('connect_id', $shop_id);
            });
        }

        $coupon_list    =   $coupon_model->select(['id', 'coupon_id', 'connect_id', 'connect_type'])->get();
        if ($coupon_list->isEmpty()) {
            return [true, []];
        } else {
            $coupon_list    =   $coupon_list->toArray();
            $good_coupon    =   $shop_coupon    =   [];
            foreach ($coupon_list as $item) {
                if (is_null($user_id)) {
                    $item['is_fetch']   =   false;
                } else {
                    //判断用户是否已经到达领取上限
                    $user_fetch         =   UserCouponModel::where(['user_id' => $user_id, 'coupon_id' => $item['coupon_id']])->count();
                    $item['is_fetch']   =   $item['coupon']['user_num'] > 0 && $user_fetch >= $item['coupon']['user_num'];
                }
                if ($item['connect_type'] == CouponConnectionModel::GOOD_CONNECT) {
                    $good_coupon[$item['connect_id']][]    =   $item;
                } else {
                    $shop_coupon[$item['connect_id']][]    =   $item;
                }
            }
            return [true, [
                'good_coupon'   =>  $good_coupon,
                'shop_coupon'   =>  $shop_coupon
            ]];
        }
    }

    /**
     * 领券中心页面
     * @return array
     */
    public function couponCenter()
    {
        $list   =   CouponModel::query()->center()->select(['id', 'unique_id', 'name', 'desc', 'picture', 'type', 'scene', 'min_price', 'sub_price', 'discount', 'expire_type', 'expire_day', 'begin_time', 'end_time'])
                    ->orderBy('sorting', 'desc')->get()->each(function (&$item) {
                        $item->begin_time   =   Carbon::createFromTimestamp($item->begin_time)->toDateTimeString();
                        $item->end_time     =   Carbon::createFromTimestamp($item->end_time)->toDateTimeString();
                        //优惠券使用场景说明
                        switch ($item->scene) {
                            case CouponModel::PLATFORM_COUPON:
                                $item->scene_desc   =   '平台通用优惠券';
                                break;

                            case CouponModel::SHOP_COUPON:
                                $item->scene_desc   =   '指定店铺优惠券';
                                break;

                            case CouponModel::GOOD_COUPON:
                                $item->scene_desc   =   '指定商品优惠券';
                                break;

                            default:
                                $item->scene_desc   =   '指定商品优惠券';
                                break;
                        }

                        //优惠券类型说明
                        switch ($item->type) {
                            case CouponModel::DECREASE_TYPE:
                                $item->type_desc    =   '满减优惠券';
                                break;

                            case CouponModel::DISCOUNT_TYPE:
                                $item->type_desc    =   '折扣优惠券';
                                break;

                            default:
                                $item->type_desc    =   '满减优惠券';
                                break;
                        }
                    });

        return [true, $list->isEmpty() ? [] : $list->toArray()];
    }

    /**
     * 用户领取优惠券
     * @param int $coupon_id  优惠券ID
     * @return array
     */
    public function couponFetch(int $coupon_id)
    {
        $user_info  =   request()->post('api_user');
        $user_id    =   $user_info['user_id'];

        /**
         * 查看优惠券详情
         */
        $coupon_info    =   CouponModel::where(['id' => $coupon_id, 'is_delete' => CouponModel::NOT_DELETE, 'is_join' => CouponModel::IS_JOIN])->select(['id', 'unique_id', 'name', 'type', 'scene', 'discount', 'expire_type', 'expire_day', 'begin_time', 'end_time', 'total_num', 'user_num', 'total_count'])->first();
        if (empty($coupon_info)) {
            return [false, '优惠券不存在'];
        }

        if ($coupon_info->total_num <= $coupon_info->total_count) {
            return [false, '优惠券已领取完毕'];
        }

        /**
         * 查看用户是否已经领取
         */
        $fetch_count    =   UserCouponModel::where(['user_id' => $user_id, 'coupon_id' => $coupon_id])->count();
        if ($coupon_info->user_num > 0 && $fetch_count >= $coupon_info->user_num) {
            return [false, '已领取过该优惠券'];
        }

        /**
         * 保存用户领取记录
         */
        $fetch_log['user_id']   =   $user_id;
        $fetch_log['fetch_type']=   UserCouponModel::SELF_FETCH;
        $fetch_log['coupon_id'] =   $coupon_id;
        $fetch_log['fetch_time']=   Carbon::now()->timestamp;
        $fetch_log['is_expire'] =   UserCouponModel::NOT_EXPIRE;
        $fetch_log['is_use']    =   UserCouponModel::NOT_USE;
        $fetch_log['is_delete'] =   UserCouponModel::NOT_DELETE;
        if ($coupon_info->expire_type == CouponModel::EXPIRE_DAY) {
            $fetch_log['begin_time']=   Carbon::now()->timestamp;
            $fetch_log['end_time']  =   $fetch_log['begin_time'] + $coupon_info->expire_day * 3600 * 24;
        } else {
            $fetch_log['begin_time']=   $coupon_info->begin_time;
            $fetch_log['end_time']  =   $coupon_info->end_time;
        }

        $fetch_result   =   UserCouponModel::create($fetch_log);
        if ($fetch_result) {
            //总领取量加1
            CouponModel::where(['id' => $coupon_id, 'is_delete' => CouponModel::NOT_DELETE, 'is_join' => CouponModel::IS_JOIN])->increment('total_count');
            return [true, '领取成功'];
        } else {
            return [false, '领取失败'];
        }
    }

    /**
     * 用户删除优惠券
     * @param array $coupon_id 优惠券ID列表
     * @return array
     */
    public function couponDelete(array $coupon_id)
    {
        $user_info  =   request()->post('api_user');
        $user_id    =   $user_info['user_id'];
        $result     =   UserCouponModel::where(['user_id' => $user_id])->whereIn('coupon_id', $coupon_id)->update(['is_delete' => UserCouponModel::IS_DELETE, 'delete_time' => Carbon::now()->timestamp]);
        if ($result) {
            return [true, '删除成功'];
        } else {
            return [false, '删除失败'];
        }
    }

}
